package com.netsdk.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.netsdk.bean.Result;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件上传工具类
 *
 * @author Yan Xu
 * @version 1.0
 * @date 2021/8/7
 * Copyright © goodits
 */
@Component
public class FileUploadUtils {

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public Result<String> upload(MultipartFile file) throws IOException {
        //上传目录地址
        String uploadDir = FilePathUtils.getUploadDir();
        if (StrUtil.isBlank(uploadDir)) {
            return ResultUtil.error("获取上传目录失败");
        }
        if (ObjectUtil.isEmpty(file)) {
            return ResultUtil.error("文件不能为空");
        }
        if (StringUtils.isEmpty(file.getOriginalFilename())) {
            return ResultUtil.error("文件名不能为空");
        }
        String suffix = null;
        String fileName = null;
        FileOutputStream fileOutputStream = null;
        try {
            //调用上传方法
            //后缀名
            suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            fileName = UUID.fastUUID() + suffix;
            String fullFileName = uploadDir + "/" + fileName;
            fileOutputStream = new FileOutputStream(fullFileName);
            IOUtils.copy(file.getInputStream(), fileOutputStream);
            //String urlPathByFileName = FilePathUtils.getUrlPathByFileName(request, fileName);
            return ResultUtil.data(fullFileName);
        } catch (Exception e) {
            //打印错误堆栈信息
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    public Result delete(String filePath) {
        File file = new File(filePath);
        if (Boolean.FALSE.equals(file.exists())) {
            return ResultUtil.error("文件不存在");
        }
        boolean delete = file.delete();
        if (Boolean.FALSE.equals(delete)) {
            return ResultUtil.error("删除失败");
        }
        return ResultUtil.success("");
    }

}
